export async function blobHandle(response) {
  const { headers: { ext = '' }, data = '', config: { params = {}, _fileBaseUrl = '' }} = response || {};

  let { headers: { name = '' }} = response || {}
  name = name ? decodeURIComponent(name) : '';
  if (data && data.type === 'text/plain') { // 文本
    const result = await readFile(data).then(res => JSON.parse(res)) || {};
    const { data: { FILE_PATH, NAME, EXT }} = result
    const url = _fileBaseUrl + FILE_PATH

    return {
      ...params,
      ...result,
      name: name || NAME || '',
      url,
      ext: ext || EXT || '',
      blobDataExt: 'json'
    }
  }

  const imgMatch = ext.match(/(jpe?g|png|gif)$/ig)
  if (imgMatch) { // 后缀类型是图片
    const blob = new Blob([data], { type: 'image/' + imgMatch[0] })
    const url = window.URL.createObjectURL(blob);
    return {
      ...params,
      name,
      url,
      ext,
      blobDataExt: imgMatch[0]
    }
  }

  const videoMatch = ext.match(/mp4$/ig)
  if (videoMatch) { // 后缀类型是图片
    const blob = new Blob([data], { type: 'video/' + videoMatch[0] })
    const url = window.URL.createObjectURL(blob);
    return {
      ...params,
      name,
      url,
      ext,
      blobDataExt: videoMatch[0]
    }
  }

  if (!ext) {
    return response
  }

  if (ext) {
    return {
      blobDataExt: 'wrongful'
    }
  }
}

async function readFile(data = '') {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsText(data, 'utf-8');
    reader.onload = function() {
      resolve(reader.result)
    }
  })
}
